package com.iflytek.uoamp.agent.monitor.sender.biz.http;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.iflytek.uoamp.agent.common.util.HttpHelper;
import com.iflytek.uoamp.agent.common.util.LogHelper;
import com.iflytek.uoamp.agent.core.sender.monitorsender.monitorinterface.IItem;
import com.iflytek.uoamp.agent.monitor.sender.biz.AbsSender;
import com.iflytek.uoamp.agent.monitor.sender.config.Config;

public class HttpSender extends AbsSender {

	private ExecutorService callTimeoutPool;
	private AtomicLong threadCounter;
	private HttpHelper helper;
	
	private Future<String> doAppend(final IItem e) throws Exception {
		return callTimeoutPool.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				StringBuffer result = new StringBuffer();
				helper.post(config.getUrl(),e.getSendPath(), JSON.toJSONString(e), result, "utf-8", config.getRequestTimeOut());
				return result.toString();
			}
		});
	}

	private Future<String> doAppendBatch(final List<IItem> e) throws Exception {
		return callTimeoutPool.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				if(e!=null && e.size()>0){
					StringBuffer result = new StringBuffer();
					helper.post(config.getUrl(),e.get(0).getSendListPath(), JSON.toJSONString(e), result, "utf-8", config.getRequestTimeOut());
					return result.toString();
				}
				return null;
			}
		});
	}

	@Override
	public Object sendBatch(List<IItem> item) {
		
		Object object = null;
		try{
			object = doAppendBatch(item).get(config.getRequestTimeOut(), TimeUnit.MILLISECONDS);
		}catch(Exception e){
			Logger.getRootLogger().error(e.getMessage(),e);
			for (IItem cur : item) {
				LogHelper.error(Config.getCache(), cur.caseToString()+"\n");
			}
		}
		return object;
	}

	
	public HttpSender(Config config) {
		super(config);
		this.threadCounter = new AtomicLong(0);
		this.helper = new HttpHelper();
		this.callTimeoutPool = Executors.newCachedThreadPool(new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) {
				Thread t = new Thread(r);
				t.setName("Http Sender thread - " + String.valueOf(threadCounter.incrementAndGet()));
				return t;
			}
		});
	}

	@Override
	public Object send(IItem item) {
		Object object = null;
		try{
			object = doAppend(item).get(config.getRequestTimeOut(), TimeUnit.MILLISECONDS);
		}catch(Exception e){
			Logger.getRootLogger().error(e.getMessage(),e);
			LogHelper.error(Config.getCache(), item.caseToString()+"\n");
		}
		return object;
	}

	
	
}
